package io.renren.modules.project.service.impl;

import io.renren.common.utils.RandomId;
import io.renren.modules.base.dao.BaseTaskInfoDao;
import io.renren.modules.base.entity.BaseWorkitemInfoEntity;
import io.renren.modules.project.dao.*;
import io.renren.modules.project.entity.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import io.renren.modules.project.service.PojectTaskService;


@Service("pojectTaskService")
public class PojectTaskServiceImpl implements PojectTaskService {
    @Autowired
    private PojectTaskDao pojectTaskDao;
    @Autowired
    private PojectWorkitemDao pojectWorkitemDao;
    @Autowired
    private ProjectEntityDao projectEntityDao;
    @Autowired
    private NotificationDao notificationDao;
    @Autowired
    private BaseTaskInfoDao baseTaskInfoDao;
    @Autowired
    private NotificationReceiverDao notificationReceiverDao;
    @Autowired
    private PojectTaskRejectDao pojectTaskRejectDao;

    @Override
    public PojectTaskEntity queryObject(String id) {
        return pojectTaskDao.queryObject(id);
    }

    @Override
    public List<PojectTaskEntity> queryList(Map<String, Object> map) {
        return pojectTaskDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return pojectTaskDao.queryTotal(map);
    }

    @Override
    public void save(PojectTaskEntity pojectTask) {
        pojectTask.setId(RandomId.createId() + "");
        pojectTaskDao.save(pojectTask);
    }

    @Override
    public void update(PojectTaskEntity pojectTask) {
        pojectTaskDao.update(pojectTask);
    }

    @Override
    public void delete(String id) {
        pojectTaskDao.delete(id);
    }

    @Override
    public void deleteBatch(String[] ids) {
        pojectTaskDao.deleteBatch(ids);
    }

    public Map<String, Object> milepost(String pojectId) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> taskMap = new ArrayList<>();
        List<PojectTaskEntity> pojectTaskEntityList = new ArrayList<>();
        ProjectEntityEntity project = projectEntityDao.queryProjectId(pojectId);
        taskMap = pojectTaskDao.queryMilepost(pojectId);
        if (taskMap.size() > 0 && taskMap != null) {
            for (int i = 0; i < taskMap.size(); i++) {
                //判断taskMap里面是否含有责任人字段
                if (!taskMap.get(i).containsKey("dutyPerson")) {
                    // 这里责任人查的是部门
                    taskMap.get(i).put("dutyPerson", "1");
                } else if ("".equals(taskMap.get(i).get("dutyPerson"))) {
                    taskMap.get(i).put("dutyPerson", "1");

                }
                if (!taskMap.get(i).containsKey("endTime")) {
                    taskMap.get(i).put("endTime", "");
                }
                String taskId = (String) taskMap.get(i).get("id");
                String projectId = (String) taskMap.get(i).get("projectId");
                PojectTaskEntity pojectTaskEntity = new PojectTaskEntity();
                pojectTaskEntity.setId(taskId);
                pojectTaskEntity.setProjectId(projectId);
                pojectTaskEntityList.add(pojectTaskEntity);
            }
            List<Map<String, Object>> workitemMap = new ArrayList<>();
            workitemMap = pojectTaskDao.queryMorkitem(pojectTaskEntityList);
            if (workitemMap.size() > 0 && workitemMap != null) {
                for (int i = 0; i < workitemMap.size(); i++) {
                    taskMap.add(workitemMap.get(i));
                }
            }
        }
        map.put("taskMap", taskMap);
        map.put("projectInfo", project);
        return map;
    }

    public void operateNotification(ProjectEntityEntity projectEntityEntity, PojectTaskEntity pojectTaskEntity, String operateType) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date operateTime = new Date();
        String operateTimeString = formatter.format(operateTime);
        List<NotificationReceiverEntity> receiverList = new ArrayList<>();
        List<NotificationEntity> notificationList = new ArrayList<>();
        NotificationEntity notificationEntity = new NotificationEntity();
        NotificationReceiverEntity pmReceiver = new NotificationReceiverEntity();
        NotificationReceiverEntity directorReceiver = new NotificationReceiverEntity();

        notificationEntity.setId(RandomId.createId() + "1");
        notificationEntity.setProjectId(projectEntityEntity.getId());
        notificationEntity.setTaskId(pojectTaskEntity.getId());
        notificationEntity.setOperateTime(operateTimeString);

        pmReceiver.setId(RandomId.createId() + "1");
        pmReceiver.setNotificationId(notificationEntity.getId());
        pmReceiver.setNotificationReceiver(projectEntityEntity.getProjectManager());
        pmReceiver.setNotificationStatus(0);

        directorReceiver.setId(RandomId.createId() + "2");
        directorReceiver.setNotificationId(notificationEntity.getId());
        directorReceiver.setNotificationReceiver(pojectTaskEntity.getTaskRespUser());
        directorReceiver.setNotificationStatus(0);

        if (operateType == "1") {
            // 已提交
            notificationEntity.setNotificationContent(projectEntityEntity.getProjectName() + "的" + pojectTaskEntity.getTaskName() + "已提交");
        } else if (operateType == "2") {
            if (StringUtils.isNotBlank(pojectTaskEntity.getRejectDesc())){
                notificationEntity.setNotificationContent(projectEntityEntity.getProjectName() + "的" + pojectTaskEntity.getTaskName() + "已驳回,驳回理由:"+pojectTaskEntity.getRejectDesc());
            }else {
                notificationEntity.setNotificationContent(projectEntityEntity.getProjectName() + "的" + pojectTaskEntity.getTaskName() + "已驳回");
            }
        } else if (operateType == "3") {
            // 任务完成有下一个任务
            notificationEntity.setNotificationContent(projectEntityEntity.getProjectName() + "的" + pojectTaskEntity.getTaskName() + "已完成");

            PojectTaskEntity pojectNextTaskEntity = pojectTaskDao.queryCurrentTaskById(projectEntityEntity.getId());

            NotificationEntity newNotificationEntity = new NotificationEntity();
            NotificationReceiverEntity newPmReceiver = new NotificationReceiverEntity();
            NotificationReceiverEntity newDirectorReceiver = new NotificationReceiverEntity();


            newNotificationEntity.setId(RandomId.createId() + "2");
            newNotificationEntity.setProjectId(projectEntityEntity.getId());
            newNotificationEntity.setTaskId(pojectNextTaskEntity.getId());
            newNotificationEntity.setOperateTime(operateTimeString);
            newNotificationEntity.setNotificationContent(projectEntityEntity.getProjectName() + "的" + pojectNextTaskEntity.getTaskName() + "已开始");

            newPmReceiver.setId(RandomId.createId() + "3");
            newPmReceiver.setNotificationId(newNotificationEntity.getId());
            newPmReceiver.setNotificationReceiver(projectEntityEntity.getProjectManager());
            newPmReceiver.setNotificationStatus(0);

            newDirectorReceiver.setId(RandomId.createId() + "4");
            newDirectorReceiver.setNotificationId(newNotificationEntity.getId());
            newDirectorReceiver.setNotificationReceiver(pojectNextTaskEntity.getTaskRespUser());
            newDirectorReceiver.setNotificationStatus(0);

            notificationList.add(newNotificationEntity);
            receiverList.add(newPmReceiver);
            receiverList.add(newDirectorReceiver);
        } else if (operateType == "4") {
            // 完成任务无下一个任务
            notificationEntity.setNotificationContent(projectEntityEntity.getProjectName() + "的" + pojectTaskEntity.getTaskName() + "已完成");
        }

        notificationList.add(notificationEntity);
        receiverList.add(pmReceiver);
        receiverList.add(directorReceiver);

        notificationDao.saveNotificationList(notificationList);
        notificationReceiverDao.saveNotificationReceiverList(receiverList);
    }


    // 提交
    @Override
    public void updataTaskSubmit(String id) {
//        PojectTaskEntity pojectTaskEntity = new PojectTaskEntity();
        PojectTaskEntity pojectTaskEntity = pojectTaskDao.queryObject(id);
        ProjectEntityEntity projectEntityEntity = projectEntityDao.queryProjectId(pojectTaskEntity.getProjectId());
//        pojectTaskEntity.setId(id);
        pojectTaskEntity.setTaskState("0");
        pojectTaskDao.update(pojectTaskEntity);
        operateNotification(projectEntityEntity, pojectTaskEntity, "1");
    }

    // 完工
    @Override
    public void updataTaskComplete(PojectTaskEntity pojectTaskEntity) {
        PojectTaskEntity pojectTaskIntactEntity = pojectTaskDao.queryObject(pojectTaskEntity.getId());
        ProjectEntityEntity projectIntactEntity = projectEntityDao.queryProjectId(pojectTaskEntity.getProjectId());

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        //修改任务状态为完工
        pojectTaskEntity.setTaskState("1");
        //修改任务实际完成时间
        pojectTaskEntity.setTaskFactEndDate(dateString);
        pojectTaskDao.update(pojectTaskEntity);
        pojectTaskEntity.setOrder(pojectTaskEntity.getOrder() + 1);
        //查出下一个任务
        PojectTaskEntity pojectTask = pojectTaskDao.queryTaskOrder(pojectTaskEntity);
        if (pojectTask != null) {
            //修改任务实际开始时间
            pojectTask.setTaskFactStartDate(dateString);
            //修改任务状态为进行中
            pojectTask.setTaskState("3");
            pojectTaskDao.update(pojectTask);

            operateNotification(projectIntactEntity, pojectTaskIntactEntity, "3");
        } else {
            //如果没有下一个任务，则全部完工
            ProjectEntityEntity projectEntityEntity = new ProjectEntityEntity();
            projectEntityEntity.setId(pojectTaskEntity.getProjectId());
            projectEntityEntity.setEndTime(dateString);
            projectEntityEntity.setProjectStatus("1");
            projectEntityDao.update(projectEntityEntity);

            operateNotification(projectIntactEntity, pojectTaskIntactEntity, "4");
        }
    }

    @Override
    public void updataTaskReject(String id,String price,Long userId) {
        PojectTaskEntity pojectTaskEntity = pojectTaskDao.queryObject(id);
        ProjectEntityEntity projectEntityEntity = projectEntityDao.queryProjectId(pojectTaskEntity.getProjectId());
        pojectTaskEntity.setTaskState("2");
        if (!"1".equals(price)){
            pojectTaskEntity.setRejectDesc(price);
            PojectTaskRejectEntity pojectTaskRejectEntity = pojectTaskRejectDao.queryTaskId(id);
            if (pojectTaskRejectEntity != null){
                pojectTaskRejectEntity.setRejectDate(new Date());
                pojectTaskRejectEntity.setRejectUserId(userId);
                pojectTaskRejectDao.update(pojectTaskRejectEntity);
            }else {
                PojectTaskRejectEntity pojectTaskRejectEntitys = new PojectTaskRejectEntity();
                pojectTaskRejectEntitys.setPojectTaskId(id);
                pojectTaskRejectEntitys.setRejectDate(new Date());
                pojectTaskRejectEntitys.setRejectUserId(userId);
                pojectTaskRejectDao.save(pojectTaskRejectEntitys);
            }
        }
        pojectTaskDao.update(pojectTaskEntity);
        operateNotification(projectEntityEntity, pojectTaskEntity, "2");
    }

    @Override
    public String queryReject(String taskId) {
        Map<String,Object> map = pojectTaskDao.queryReject(taskId);
        if (map != null){
            String rejectDesc = (String) map.get("rejectDesc");
            String userName = (String)map.get("userName");
            Date rejectDate = (Date)map.get("rejectDate");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String date = formatter.format(rejectDate);
            String src = "该节点于" + date + "由" + userName + "驳回，驳回理由是：" + rejectDesc;
            return src;
        }
        return null;
    }

    public List<Map<String, Object>> getDoingTaskList(String userId, List<String> roleIdList) {

        boolean isOk = false;
        Map<String, Object> mapDuty = new HashMap<>();
        Map<String, Object> mapPm = new HashMap<>();
        mapDuty.put("userId", userId);
        mapPm.put("userId", userId);
        List<Map<String, Object>> taskDutyList = new ArrayList<>();   // 负责人任务列表
        List<Map<String, Object>> taskPmList = new ArrayList<>(); // 经理任务列表
        List<Map<String, Object>> taskList = new ArrayList<>();
        if (roleIdList != null && roleIdList.size() > 0) {
            for (int i = 0; i < roleIdList.size(); i++) {
                //为项目经理
                if ("2".equals(roleIdList.get(i))) {
                    isOk = true;
                    break;
                }
            }
        }
        //获取任务负责人所负责任务所在的项目(包含此项目)id列表
        List<String> projectList = projectEntityDao.userQueryTaskWithPm(userId);
        if (projectList.size() > 0) {
            mapDuty.put("projectList", projectList);
            taskDutyList = pojectTaskDao.queryDutyDoingTaskList(mapDuty);
        }
        if (isOk) {
            // 经理所负责项目id列表
            if (!"".equals(userId)) {
                List<String> tempProjectList = projectEntityDao.queryManagerOnlyList(userId);
                if (tempProjectList.size() > 0) {
                    mapPm.put("projectList", tempProjectList);
                    taskPmList = pojectTaskDao.queryPmDoingTaskList(mapPm);
                }
            }
        }
        if (taskDutyList.size() > 0) {
            for (int i = 0; i < taskDutyList.size(); i++) { // 负责人
                taskList.add(taskDutyList.get(i));
            }
        }

        if (taskPmList.size() > 0) {
            for (int i = 0; i < taskPmList.size(); i++) { // 项目经理
                taskList.add(taskPmList.get(i));
            }
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date currentDate = new Date();
        System.out.println("*******任务*********" + taskList.size());

        for (int k = 0; k < taskList.size(); k++) {
            String startDateString = (String) taskList.get(k).get("taskStart");
            int durationRequire = (int) taskList.get(k).get("durationRequire");
            try {
                Date startDate = formatter.parse(startDateString);
                long differentialTime = (startDate.getTime() - currentDate.getTime()) / (24 * 60 * 60 * 1000) + durationRequire;
                taskList.get(k).put("differentialTime", differentialTime);
            } catch (ParseException px) {
                px.printStackTrace();
            }
        }
        return taskList;
    }

    @Override
    public List getMilepostTask(String projectId) {
        List list = new ArrayList();
        List<Map<String, Object>> taskList = pojectTaskDao.getProjectTask(projectId);
        for (int i = 0; i < taskList.size(); i++) {
            if (taskList.get(i).get("taskFactStartDate") != null && !"".equals(taskList.get(i).get("taskFactStartDate")) &&
                    taskList.get(i).get("taskFactenddate") == null || "".equals(taskList.get(i).get("taskFactenddate"))) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date currentDate = new Date();
                int durationRequire = (int) taskList.get(i).get("durationRequire");
                try {
                    Date startDate = formatter.parse((String) taskList.get(i).get("taskFactStartDate"));
                    long differentialTime = (startDate.getTime() - currentDate.getTime()) / (24 * 60 * 60 * 1000) + durationRequire;
                    if (differentialTime < 0) {
                        // 已超期
                        taskList.get(i).put("taskState", "已超期");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        List<Map<String, Object>> workitemList = pojectTaskDao.getProjectWorkitem(projectId);
        list.add(taskList);
        list.add(workitemList);
        return list;
    }

    @Override
    public void updateOrder(List<PojectTaskEntity> pojectTaskEntities) {
        pojectTaskDao.updateOrder(pojectTaskEntities);
    }

    @Override
    public void deleteTask(String id, List<PojectTaskEntity> pojectTaskEntities) {
        pojectTaskDao.delete(id);
        pojectWorkitemDao.deleteWorkitem(id);
        pojectTaskDao.updateOrder(pojectTaskEntities);
    }

    @Override
    public void deleteWorkitem(String id) {
        pojectWorkitemDao.delete(id);
    }

    @Override
    public List queryTemplateTask(String projectId) {
        List list = new ArrayList();
        List<Map<String, Object>> task = baseTaskInfoDao.queryProjectIdTask(projectId);
        List<Map<String, Object>> taskList = baseTaskInfoDao.queryNoTemplateTask();
        taskList.removeAll(task);
        List<String> taskIdList = new ArrayList<>();
        String[] taskId = null;
        if (taskList != null && taskList.size() > 0) {
            for (int i = 0; i < taskList.size(); i++) {
                taskIdList.add((String) taskList.get(i).get("id"));
            }
            if (taskIdList != null && taskIdList.size() > 0) {
                taskId = taskIdList.toArray(new String[taskIdList.size()]);
            }
            list.add(taskList);
        }
        return list;
    }

    @Override
    public void projectAddTask(List<PojectTaskEntity> pojectTaskEntities) {
        List<PojectTaskEntity> pojectTaskEntityList = new ArrayList<>();
        List<PojectWorkitemEntity> pojectWorkitemEntityList = new ArrayList<>();
        List<PojectTaskEntity> queryPojectTask = pojectTaskDao.queryTask(pojectTaskEntities.get(0).getProjectId());
        if (queryPojectTask != null && queryPojectTask.size() > 0) {
            for (int i = 0; i < pojectTaskEntities.size(); i++) {
                String projectTaskId = RandomId.createId() + "" + i;
                PojectTaskEntity pojectTask = new PojectTaskEntity();
                pojectTask.setId(projectTaskId);
                pojectTask.setTaskId(pojectTaskEntities.get(i).getTaskId());
                pojectTask.setProjectId(pojectTaskEntities.get(i).getProjectId());
                pojectTask.setTaskName(pojectTaskEntities.get(i).getTaskName());
                pojectTask.setTaskRespUser(pojectTaskEntities.get(i).getTaskRespUser());
                pojectTask.setTaskState("4");
                pojectTask.setPhaseId(pojectTaskEntities.get(i).getPhaseId());
                pojectTask.setOperationType("0");
                pojectTask.setOrder(queryPojectTask.get(0).getOrder() + i + 1);
                pojectTaskEntityList.add(pojectTask);
                List<BaseWorkitemInfoEntity> baseWorkitemInfoEntities = pojectTaskDao.queryPojectWorkitem(pojectTaskEntities.get(i).getTaskId());
                if (baseWorkitemInfoEntities != null && baseWorkitemInfoEntities.size()>0){
                    for (int k = 0 ; k<baseWorkitemInfoEntities.size();k++){
                        PojectWorkitemEntity pojectWorkitemEntity = new PojectWorkitemEntity();
                        pojectWorkitemEntity.setId(RandomId.createId() + "" + k);
                        pojectWorkitemEntity.setProjectId(pojectTaskEntities.get(i).getProjectId());
                        pojectWorkitemEntity.setTaskId(projectTaskId);
                        pojectWorkitemEntity.setWorkitemName(baseWorkitemInfoEntities.get(k).getWorkitemName());
                        pojectWorkitemEntity.setDeliveryDesc(baseWorkitemInfoEntities.get(k).getDeliveryGoods());
                        pojectWorkitemEntity.setOrder(baseWorkitemInfoEntities.get(k).getOrder());
                        pojectWorkitemEntity.setCreationUser(pojectTaskEntities.get(i).getTaskRespUser());
                        //我要获取当前的日期
                        Date date = new Date();
                        //设置要获取到什么样的时间
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        //获取String类型的时间
                        String createdate = sdf.format(date);
                        pojectWorkitemEntity.setCreationTime(createdate);
                        pojectWorkitemEntityList.add(pojectWorkitemEntity);
                    }
                }
            }
            pojectWorkitemDao.insertWorkitem(pojectWorkitemEntityList);
            pojectTaskDao.projectAddTask(pojectTaskEntityList);
        }
    }

}
